from datetime import datetime
from peewee import *
from typing import Optional
from .database_pool import DatabasePool

db = DatabasePool()

class DataDictionary(Model):
    # 字典键
    dict_key = CharField(max_length=50, unique=True)
    # 字典值
    dict_value = TextField()
    # 字典描述
    dict_desc = TextField(null=True)
    # 创建时间
    create_time = DateTimeField(default=datetime.now)
    # 更新时间
    update_time = DateTimeField(default=datetime.now)

    class Meta:
        database = db.database
        table_name = "data_dictionary"


class DataDictionaryService:
    # 增加数据字典项
    def add_dictionary_item(self, dict_key: str, dict_value: str, dict_desc: Optional[str] = None):
        try:
            DataDictionary.create(
                dict_key=dict_key,
                dict_value=dict_value,
                dict_desc=dict_desc,
                create_time=datetime.now(),
                update_time=datetime.now()
            )
            print(f"字典项 {dict_key} 已添加成功。")
        except IntegrityError:
            print(f"字典键 {dict_key} 已存在，无法重复添加。")

    # 更新数据字典项
    def update_dictionary_item(self, dict_key: str, dict_value: Optional[str] = None, dict_desc: Optional[str] = None):
        try:
            item = DataDictionary.get(DataDictionary.dict_key == dict_key)
            if dict_value is not None:
                item.dict_value = dict_value
            if dict_desc is not None:
                item.dict_desc = dict_desc
            item.update_time = datetime.now()
            item.save()
            print(f"字典项 {dict_key} 已更新成功。")
        except DoesNotExist:
            print(f"字典键 {dict_key} 不存在，无法更新。")

    # 查询所有数据字典项
    def get_all_items(self):
        items = DataDictionary.select()
        return list(items)

    # 根据键查询数据字典项
    def get_item_by_key(self, dict_key: str) -> Optional[DataDictionary]:
        try:
            item = DataDictionary.get(DataDictionary.dict_key == dict_key)
            return item
        except DoesNotExist:
            print(f"未找到字典键 {dict_key} 的记录。")
            return None

    # 删除数据字典项
    def delete_item_by_key(self, dict_key: str):
        try:
            item = DataDictionary.get(DataDictionary.dict_key == dict_key)
            item.delete_instance()
            print(f"字典项 {dict_key} 已被删除。")
        except DoesNotExist:
            print(f"未找到字典键 {dict_key} 的记录，无法删除。")
